import React, { Component } from 'react'
import { Alert, BackHandler, RefreshControl, TouchableOpacity, FlatList, Text, ActivityIndicator, ScrollView, View} from 'react-native'
import Button from '../Components/Button'
import { connect } from 'react-redux'

import AddressActions from '../Redux/AddressRedux'

import AppConfig from '../Config/AppConfig'
const domain = AppConfig.domain

import Empty from '../Components/Empty'

// Styles
import styles from './Styles/AddressScreenStyle'

class AddressScreen extends Component {
  static navigationOptions = ({navigation}) => {
    const { state, setParams } = navigation
    const { params = {} } = state
    let headerRight = null
    if (params.manager) {
      headerRight = <TouchableOpacity onPress={()=>setParams({manager:false})}><Text style={{paddingRight:10}}>取消</Text></TouchableOpacity>
    } else {
      headerRight = <TouchableOpacity onPress={()=>setParams({manager:true})}><Text style={{paddingRight:10}}>管理</Text></TouchableOpacity>
    }
    return {
      title: '地址管理',
      headerRight: headerRight
    }
  }
  constructor(props) {
    super(props)
    const { state } = this.props.navigation
    this.state = {
      choice: state.params ? state.params.choice : false,
      refreshing: false
    }
  }
  componentDidMount() {
    this.props.navigation.setParams({manager:false})
    this.props.getAddress(this.props.token)
    BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
  }
  componentWillUnmount() {
    BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
  }
  componentDidUpdate(prevProps, prevState) {
    if(prevProps.address.fetching
      && prevState.refreshing
      && !this.props.address.error) {
      this.setState({refreshing:false})
    }
  }
  onBackPress = () => {
    this.props.navigation.goBack()
    return true
  }
  _onRefresh() {
    this.setState({refreshing:true})
    this.props.getAddress(this.props.token)
  }
  _onChoice(index) {
    this.props.setActive(index)
    this.props.navigation.goBack()
  }
  _onCreate() {
    this.props.navigation.navigate('WebScreen',{title:'添加地址',link:domain+'/api/address/add_address?token='+this.props.token})
  }
  _onEdit(index) {
    //this.props.navigation.navigate('AddressEditScreen', {index:index})
    this.props.navigation.navigate('WebScreen', {title:'编辑地址',link:domain+'/api/address/get_address?token='+this.props.token+'&id='+index})
  }
  _onDelete(index, id) {
    Alert.alert('提醒','确认删除?',[
      {text:'取消', onPress:()=>null},
      {text:'确定', onPress:()=>this.props.delete(this.props.token, index, id)}
    ])
    
  }
  render () {
    const { state, navigate, goBack } = this.props.navigation
    const { params = {} } = state
    if (this.props.address.fetching) {
      return <ActivityIndicator style={{marginTop:20}} />
    }
    if (!this.props.address.payload) {
      return <Empty />
    }
    return (
      <View style={styles.container}>
        <FlatList
          keyExtractor={(item,index)=>index}
          refreshControl={
            <RefreshControl
              refreshing={this.state.refreshing}
              onRefresh={this._onRefresh.bind(this)}
            />
          }
          data={this.props.address.payload}
          renderItem={({item, index}) =>
            <View
              key={index}
              style={styles.item}>
              <View style={{flex:1}}>
                <Text style={styles.name}>
                  {item.name}  {item.mobile}</Text>
                <Text style={styles.description}>
                  {item.area} {item.address}</Text>
              </View>
              {params.manager ? (
                <View>
                  <Button hollow small danger
                    onPress={()=>this._onDelete(index, item.id)}
                    title='删除' />
                </View>
              ) : (
                <View>
                  {this.state.choice &&
                    <Button hollow small style={{marginBottom:5}}
                      onPress={()=>this._onChoice(index)}
                      title='选择' />
                  }
                  <Button hollow small
                    onPress={()=>this._onEdit(item.id)}
                    title='编辑' />
                </View>
              )}
            </View>
          }
        />
        <TouchableOpacity
          onPress={()=>this._onCreate()}
          style={styles.bottomButton}>
          <Text style={{color:'white'}}>添加地址</Text>
        </TouchableOpacity>
      </View>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    token: state.user.payload.token,
    address: state.address,
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    getAddress: (token) => dispatch(AddressActions.getAllRequest(token)),
    setActive: (index) => dispatch(AddressActions.activeSet(index)),
    delete: (token,index,id) => dispatch(AddressActions.deleteRequest(token,index,id))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(AddressScreen)
